package com.acme.security.config;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {



	@Override
	protected void configure(HttpSecurity http) throws Exception {

		http.authorizeRequests()
		.antMatchers("/admin/**").hasRole("ADMIN")
		.antMatchers("/AdminAcceptedClaims/**").hasRole("ADMIN")
		.antMatchers("/AdminAllClaims/**").hasRole("ADMIN")
		.antMatchers("/AdminRejectedClaims/**").hasRole("ADMIN")
		.antMatchers("/AdminUsers/**").hasRole("ADMIN")
		.antMatchers("/Claim/**").hasRole("USER")
		.antMatchers("/ClaimCreation/**").hasRole("USER")
		.antMatchers("/ClaimCreaion2/**").hasRole("USER")
		.antMatchers("/ClaimPortal/**").hasRole("USER")
		.antMatchers("ClaimRegReview/**").hasRole("USER")
		.antMatchers("/ForgotPassword/**").permitAll()
		.antMatchers("/ViewClaim/**").hasRole("USER")
		.antMatchers("/ViewCreatedClaim/**").hasRole("USER")
		.antMatchers("/HospitalInfo/**").hasRole("USER")
		.antMatchers("/InjuryInfo/**").hasRole("USER")
		.antMatchers("/MedicareCoverageInfo/**").hasRole("USER")
		.antMatchers("/PrivateCoverageInfo/**").hasRole("USER")
		.antMatchers("/MyAccount/**").hasRole("USER")
		.antMatchers("/InsuranceAdjuster/**").hasAnyRole("ADJUSTER", "ADMIN")
		.antMatchers("/resources/**").permitAll()
		.antMatchers("/reset/**").permitAll()
		.antMatchers("/ResetMessage/**").permitAll()
		.and().formLogin().loginPage("/Login").permitAll()
		.failureUrl("/Login?error")
		.usernameParameter("username").passwordParameter("password")
		.and().logout().logoutUrl("/Logout")
		.and().logout().logoutSuccessUrl("/Login?logout")
		.and().exceptionHandling().accessDeniedPage("/403Catch")
		.and().csrf()
		.and().requiresChannel()
		.anyRequest().requiresSecure()		
		.and().csrf().disable();
	}	


	@Bean
	public PasswordEncoder passwordEncoder()
	{
		PasswordEncoder encoder = new BCryptPasswordEncoder();
		return encoder;
	}

	@Resource(name="authService")
	private UserDetailsService userDetailsService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception 
	{		
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}
}